import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';

class BalloonPainter extends CustomPainter {
  final double originalWidth = 1024.0;
  final double originalHeight = 1024.0;
  final PictureInfo pictureInfo;

  const BalloonPainter({required this.pictureInfo});

  @override
  void paint(Canvas canvas, Size size) {
    // 计算缩放比例
    final scaleX = size.width / originalWidth;
    final scaleY = size.height / originalHeight;
    final scale = min(scaleX, scaleY);

    // 应用缩放变换
    final transform = Matrix4.identity()..scale(scale, scale);
    canvas.transform(transform.storage);

    // 绘制图片
    canvas.drawPicture(pictureInfo.picture);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

class Balloon extends StatefulWidget {
  final String rawSvg;

  const Balloon({
    super.key,
    String? color,
    String? lineColor = 'rgba(250, 250, 250, 0.5)',
    String? reflectiveSpotColor = 'rgba(240, 240, 240, 0.3)',
  }) : rawSvg = '''
    <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
      <path
        d="M797.51444445 400.31c0.01 147.84-108.14 347.1-285.63 347.1s-273.23-192.49-277.2-324.2C228.65444445 223.14 337.19444445 84.14 514.69444445 84.14c141.41 0 282.81 138.67 282.82 316.17z"
        fill="$color" />
      <path
        d="M527.12444445 742.4h-20.24l-31.39 56.45 0.39 10.65h83.24l-0.19-11.26z"
        fill="$color" />
      <path
        d="M444.96444445 962.96l-30.53-20.89s51.81-29.5 67.28-55.84c16.28-27.72 14.67-76.73 14.67-76.73h40.17s-5.02 58.48-10.77 72.41c-22.17 53.73-80.82 81.05-80.82 81.05z"
        fill="$lineColor" />
      <path
        d="M709.20444445 256.23c19.61 63.32 15.97 122.85-17.76 122.85-48.61 0-50.75-33.65-74.53-78.3-32.94-61.87-20.68-105.76 20.3-105.76 33.73 0 57.85 15.54 71.99 61.21z"
        fill="$reflectiveSpotColor" />
    </svg>
  ''';

  @override
  State<Balloon> createState() => _BalloonState();
}

class _BalloonState extends State<Balloon> {
  PictureInfo? pictureInfo;

  @override
  void initState() {
    super.initState();
    vg.loadPicture(SvgStringLoader(widget.rawSvg), null).then((pic) {
      setState(() {
        pictureInfo = pic;
      });
    });
  }

  @override
  void dispose() {
    pictureInfo?.picture.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(10),
      child: AspectRatio(
        aspectRatio: 1,
        child: CustomPaint(
          painter: pictureInfo != null
              ? BalloonPainter(
                  pictureInfo: pictureInfo!,
                )
              : null,
        ),
      ),
    );
  }
}
